package com.imooc.controller.interceptor;

import com.imooc.controller.BaseController;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;


@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;


    /**
     * 进入controller之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(userToken)) {
            return resultJson(response, "请登录...");
        }
        String uniqueToken = redisOperator.get(BaseController.REDIS_USER_TOKEN + ":" + userId);
        if (StringUtils.isBlank(uniqueToken)) {
            return resultJson(response, "请登录...");
        }
        if (!userToken.equals(uniqueToken)) {
            return resultJson(response, "账号在异地登录...");
        }

        log.info("进入拦截器，放行.....");

        /*
         * true：请求在经过验证以后是ok的，可以放行
         * false：请求被拦截，被驳回，验证出问题
         */
        return true;
    }

    private boolean resultJson(HttpServletResponse response, String errorMsg) {
        OutputStream outputStream = null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        String toJson = JsonUtils.objectToJson(IMOOCJSONResult.errorMsg(errorMsg));
        try {
            outputStream = response.getOutputStream();
            outputStream.write(toJson.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }


    /**
     * 进入controller之后，渲染视图之前
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
